# -*- coding: utf-8 -*-
import hashlib
import json
import urllib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now, utc_to_local

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://pay.drippayment.com/pay/onlinepay.json'

APP_CONF = {
    '0000057': {
        'API_KEY': '3FFF827784C17862'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['signData']
    params.pop('signData')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("trpay sign: %s, calculated sign: %", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def build_html(code_url):
    html = u"<head><title>请打开微信扫码支付</title></head>"
    html += u"<body><div style='text-align: center'><span>请将下面二维码截图，然后用微信扫一扫</span></div>"
    html += "<div style='text-align: center'><img src='{}' /></div>".format(code_url)
    html += "</body>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    service = info['service']  # wechat or alipay
    chn_name = '0003' if service == 'alipay' else '0002'
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('versionId', '001'),
        ('businessType', '1100'),
        ('transChanlName', chn_name),
        ('merId', app_id),
        ('orderId', str(pay.id)[2:]),
        ('transDate', local_now().strftime('%Y%m%d%H%M%S')),
        ('transAmount', str(int(pay_amount))),
        ('backNotifyUrl', '{}/pay/api/{}/trpay/'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH)),
        ('orderDesc', urllib.quote(u'商品'.encode('gbk'))),
        ('dev', '{"app_id": "%s"}' % app_id),
    ))
    parameter_dict['signData'] = generate_sign(parameter_dict, api_key)
    parameter_dict['signType'] = 'MD5'
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    if response.status_code == 200:
        # response text is a pure html text
        res_obj = json.loads(response.text)
        if service == 'alipay':
            charge_resp.update({
                'charge_info': res_obj['codeUrl'],
            })
        else:
            charge_resp.update({
                'charge_info': build_html(res_obj['codeImgUrl']),
            })
        third_id = res_obj.get('ksPayOrderId')
        order_db.fill_third_id(pay.id, third_id)
        _LOGGER.info("trpay data after charge: %s", res_obj)
    else:
        _LOGGER.warn('trpay data error, status_code: %s', response.status_code)
    return charge_resp


def check_notify_sign(request):
    data = dict(request.POST.iteritems())
    _LOGGER.info("trpay notify data: %s", data)
    cpp_param = json.loads(data['dev'])
    app_id = cpp_param.get('app_id')
    api_key = _get_api_key(app_id)
    verify_notify_sign(data, api_key)
    pay_id = '16' + data['orderId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('trpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = data['refcode']
    mch_id = pay.mch_id
    trade_no = data['ksPayOrderId']
    total_fee = float(data['transAmount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '00':
        _LOGGER.info('trpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    service = pay_order.service
    pay_id = pay_order.id
    charge_resp = {}
    api_key = _get_api_key(app_id)
    chn_name = '0003' if service == 'alipay' else '0002'
    parameter_dict = OrderedDict((
        ('versionId', '001'),
        ('businessType', '1200'),
        ('merId', app_id),
        ('transChanlName', chn_name),
        ('orderId', str(pay_id)[2:]),
        ('transDate', utc_to_local(pay_order.updated_at).strftime('%Y%m%d%H%M%S')),
        ('ksPayOrderId', pay_order.third_id),
    ))
    parameter_dict['signData'] = generate_sign(parameter_dict, api_key)
    parameter_dict['signType'] = 'MD5'
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    if response.status_code == 200:
        # response text is a pure html text
        data = json.loads(response.text)
        print data
        trade_status = data['refcode']
        if trade_status == '00':
            trade_no = data['ksPayOrderId']
            total_fee = float(data['transAmount'])
            extend = {
                'trade_status': trade_status,
                'trade_no': trade_no,
                'total_fee': total_fee
            }
            _LOGGER.info('trpay query order success, mch_id:%s pay_id:%s',
                         pay_order.mch_id, pay_order.id)
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('trpay data error, status_code: %s', response.status_code)
    return charge_resp
